﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace BlueAd
{
    public class Scheduler : List<Campain>
    {
        private Thread _engine;
        private Object _locker;
        private bool _running;
        public event EventHandler<RunningCampain> ActiveCampain;
        public event EventHandler<NotRunningCampain> InactiveCampain;

        public Scheduler()
        {
            _engine= new Thread(Engine);
            _engine.Priority = ThreadPriority.AboveNormal;
            _locker = new object();
            _running = false;
        }

        public Scheduler(List<Campain> campains): this()
        {
            AddRange(campains);
        }


       public void AddRange(List<Campain> campains)
       {
           Clear();
           foreach (Campain campain in campains)
           {
               Add(campain);    
           }
       }

        public new void Add(Campain campain)
        {
            if(!Contains(campain))
                base.Add(campain);
        }

        private void Engine()
        {
            while (_running)
            {
                lock (_locker)
                {
                    foreach (Campain campain in this)
                    {
                        if(campain.Start < DateTime.Now && campain.End > DateTime.Now)
                        {
                            if(campain.Enabled)
                                if (ActiveCampain != null)
                                    ActiveCampain(campain, null);
                        }
                        else
                        {
                            if (InactiveCampain != null)
                                InactiveCampain(campain, null);
                        }
                    }
                }
                Thread.Sleep(10000);
            }
        }

        public void Start()
        {
            _running = true;
            if(_engine.ThreadState != ThreadState.Running)
            {
                _engine = new Thread(Engine);
                _engine.Start();
            }
        }

        public bool Stop()
        {
            _running = false;
            _engine.Abort();
            return true;
        }
    }
    public class RunningCampain : EventArgs
    {
        private Campain Campain { get; set; }

    }
    public class NotRunningCampain : EventArgs
    {
        private Campain Campain { get; set; }

    }

}
